package cn.aitrox.ry.service.config.service.impl;

import cn.aitrox.ry.bean.RespResult;
import cn.aitrox.ry.enumtype.RespCodeEnum;
import cn.aitrox.ry.service.config.dao.ToolDao;
import cn.aitrox.ry.service.config.entity.ToolEntity;
import cn.aitrox.ry.service.config.service.ToolService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ToolServiceImpl implements ToolService {

    @Autowired
    private ToolDao toolDao;

    @Transactional
    @Override
    public RespResult edit(Integer id, String name, String remark) {
        // 校验名称是否重复
        if (nameExisted(id, name)) {
            return RespResult.secByError(RespCodeEnum.EXISTED.getCode(), "名称已存在");
        }

        ToolEntity toolEntity = new ToolEntity(id,name,null,null,remark);
        toolDao.updateByIdSelective(toolEntity);

        return RespResult.ok();
    }

    @Override
    public String maxValue() {
        return toolDao.maxValue();
    }

    @Override
    public PageInfo<ToolEntity> search(Integer page, Integer pageSize, String name, List<String> valueList) {
        String likeName = null;
        if(StringUtils.isNotEmpty(name)) {
            likeName = "%" + name + "%";
        }
        return toolDao.search(page, pageSize, likeName, valueList);
    }

    private Boolean  nameExisted(Integer id, String name) {
        ToolEntity cond = new ToolEntity();
        cond.setName(name);
        List<ToolEntity> listByName = toolDao.findByCondition(cond, null);
        return listByName.stream().filter(x -> !x.getId().equals(id) && x.getName().equals(name)).count() > 0;
    }
}
